package com.xiaoheng999.miya.spingmvc.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.xiaoheng999.miya.domain.User;
import com.xiaoheng999.miya.service.UserService;
import com.xiaoheng999.miya.spingmvc.model.Student;

@Controller
public class StudentController {
	
	@Autowired
	private UserService userService;

    @RequestMapping(value = "/student", method = RequestMethod.GET)
    public ModelAndView student() {
        Student stu = new Student();
        User user = userService.selectByPrimaryKey(1);
        stu.setName(user.getUserName());
        stu.setAge(25);
        return new ModelAndView("pages/springmvc/student", "student", stu);
    }
    
    @ModelAttribute("student")
    public Student createStudentModel() {    
       return new Student();
    }
    
    
    @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
    public String addStudent(@ModelAttribute("student")  @Validated Student student, BindingResult bindingResult,ModelMap model) {
    	if (bindingResult.hasErrors()) {
            return "pages/springmvc/student";
         }
        model.addAttribute("name", student.getName());
        model.addAttribute("age", student.getAge());
        model.addAttribute("id", student.getId());

        return "pages/springmvc/result";
    }
}
